//
// Created by meng on 24-11-6.
//

#include "LogicSystem.h"

LogicSystem::LogicSystem(): _b_stop(false) {
    RegisterCallBacks();
    _worker_thread = thread(&LogicSystem::DealMsg, this);
}

LogicSystem::~LogicSystem() {
    _b_stop = true;
    _consume.notify_one();
    _worker_thread.join();
}

void LogicSystem::PostMsgToQueue(const std::shared_ptr<LogicNode> &msg) {
    unique_lock<mutex> lock(_mutex);
    _msg_que.push(msg);
    if (_msg_que.size() == 1) {
        _consume.notify_one();
    }
}

void LogicSystem::DealMsg() {
    while (true) {
        unique_lock<mutex> lock(_mutex);
        while (_msg_que.empty() && _b_stop == false) {
            _consume.wait(lock);
        }
        if (_b_stop == true) {
            while (!_msg_que.empty()) {
                const auto msg_node = _msg_que.front();
                short msg_id = msg_node->_recv_node->_msg_id;
                clog << "接收数据的ID = " << msg_id << endl;
                auto call_back_iter = _fun_callbacks.find(msg_id);
                if (call_back_iter == _fun_callbacks.end()) {
                    _msg_que.pop();
                    cerr << "此消息ID不在定义的ID中" << endl;
                    continue;
                }
                call_back_iter->second(msg_node->_session, msg_node->_recv_node->_msg_id, msg_node->_recv_node->_data);
                _msg_que.pop();
            }
            break;
        }

        const auto msg_node = _msg_que.front();
        short msg_id = msg_node->_recv_node->_msg_id;
        clog << "接收数据的ID = " << msg_id << endl;
        auto call_back_iter = _fun_callbacks.find(msg_id);
        if (call_back_iter == _fun_callbacks.end()) {
            _msg_que.pop();
            cerr << "此消息ID不在定义的ID中" << endl;
            continue;
        }
        call_back_iter->second(msg_node->_session, msg_node->_recv_node->_msg_id, msg_node->_recv_node->_data);
        _msg_que.pop();
    }
}

void LogicSystem::RegisterCallBacks() {
    // _fun_callbacks[MSG_HELLO_WORD] = bind(&LogicSystem::HelloWordCallBack, this, std::placeholders::_1,
    //                                       std::placeholders::_2, std::placeholders::_3);

    _fun_callbacks[MSG_HELLO_WORD] = [this](const shared_ptr<Session> &session, const short id, const string &msg) {
        this->HelloWordCallBack(session, id, msg);
    };
}

void LogicSystem::HelloWordCallBack(const shared_ptr<Session> &session, const short msg_id, const string &msg_data) { // NOLINT(*-convert-member-functions-to-static)
    clog << "进行逻辑处理，信息来自 = " << session << " ，处理信息ID = " << msg_id << " ，JSON内容 = " << msg_data << endl;
}
